package cn.iocoder.yudao.module.service.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.framework.websocket.core.session.WebSocketSessionManager;
import cn.iocoder.yudao.framework.websocket.core.util.WebSocketFrameworkUtils;
import cn.iocoder.yudao.module.service.service.customer.ServiceCustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ServiceUpdateCustomerStatusJob implements JobHandler {

    @Resource
    private WebSocketSessionManager webSocketSessionManager;

    @Resource
    private ServiceCustomerService serviceCustomerService;

    @Override
    @TenantJob
    public String execute(String param) throws Exception {
        Collection<WebSocketSession> sessionList = webSocketSessionManager.getSessionList(UserTypeEnum.MEMBER.getValue());
        if (CollectionUtil.isEmpty(sessionList)) {
            serviceCustomerService.updateAllCustomerOffLine();
            return "Session is empty!";
        }
        List<LoginUser> collect = sessionList.stream().map(WebSocketFrameworkUtils::getLoginUser).collect(Collectors.toList());
        Set<Long> loginUserSet = collect.stream().map(LoginUser::getId).collect(Collectors.toSet());
        serviceCustomerService.updateCustomerStatus(loginUserSet);
        return null;
    }
}
